package com.tnl.web.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.biz.hunter.dao.CityDAO;
import com.biz.hunter.dao.CompanyDAO;
import com.biz.hunter.dao.DomainDAO;
import com.biz.hunter.dao.EmployeeDAO;
import com.biz.hunter.dao.JobTitleDAO;
import com.biz.hunter.dao.PersonDAO;
import com.biz.hunter.dao.WXUserDAO;
import com.biz.hunter.db.entity.City;
import com.biz.hunter.db.entity.Company;
import com.biz.hunter.db.entity.Domain;
import com.biz.hunter.db.entity.Employee;
import com.biz.hunter.db.entity.JobTitle;
import com.biz.hunter.db.entity.Person;
import com.biz.hunter.db.entity.UserInfo;
import com.biz.wechat.annotation.OAuthRequired;
import com.tnl.web.config.controller.Authentication;
import com.tnl.web.domain.AdminUser;
import com.tnl.web.dto.jqGridRequestObject;
import com.tnl.web.dto.jqGridResponseObject;
import com.tnl.web.entity.ErrorMsg;
import com.tnl.web.util.qualifiers.AuditIt;

@Controller
public class EmployeeController {

	private static final Logger logger = LoggerFactory.getLogger(EmployeeController.class);

	@Autowired
	private WXUserDAO userDAO;
	@Autowired
	private DomainDAO domainDAO;
	@Autowired
	private CompanyDAO companyDAO;
	@Autowired
	private EmployeeDAO empDAO;
	@Autowired
	private PersonDAO personDAO;
	@Autowired
	private JobTitleDAO roleDAO;
	@Autowired
	private CityDAO cityDAO;
	@Autowired
	private Authentication authentication;

	// 候选人列表
	@AuditIt(module = "employee", action = "employee_view", description = "show the employee index page")
	@RequestMapping(value = "admin/employee/manage.page", method = RequestMethod.GET)
	public String toList(HttpServletRequest request, Model model) {

		HttpSession session = request.getSession();
		String userId = (String) session.getAttribute("UserId");

		logger.debug("userid is " + userId);
		if (!StringUtils.hasText(userId)) {
			logger.info("Login is needed.");
			return "admin/platformadminlogin";
		}

		AdminUser user = authentication.getCurrentUser();
		if (user == null) {
			logger.error("can not get the user info" + userId);
			return "admin/platformadminlogin";
		}

		List<Company> companies = companyDAO.getALL();
		model.addAttribute("companies", companies);
		List<City> cities = cityDAO.getALL();
		model.addAttribute("cities", cities);
		List<JobTitle> roles = roleDAO.getALL();
		model.addAttribute("roles", roles);

		return "admin/employee/employeelist";
	}

	// 显示编辑表单页面
	@AuditIt(module = "employee", action = "editEmployee", description = " the employee edit page")
	@RequestMapping(value = "admin/employee/form.page", method = RequestMethod.GET)
	public String toEdit(HttpServletRequest request, Model model) {

		String empId = request.getParameter("empid");
		if (StringUtils.hasText(empId)) {
			Employee emp = empDAO.getById(Integer.parseInt(empId));
			model.addAttribute("employee", emp);
		} else {
			return "admin/errorpage";
		}

		List<Company> companies = companyDAO.getALL();
		List<JobTitle> roles = roleDAO.getALL();
		model.addAttribute("companies", companies);
		model.addAttribute("roles", roles);
		List<City> cities = cityDAO.getALL();
		model.addAttribute("cities", cities);

		return "admin/employee/employeeeditform";
	}

	@AuditIt(module = "employee", action = "createEmployee", description = " the employee create page")
	@RequestMapping(value = "admin/employee/toCreate.page", method = RequestMethod.GET)
	public String toCreate(HttpServletRequest request, Model model) {
		Employee emp = new Employee();
		model.addAttribute("employee", emp);
		List<Company> companies = companyDAO.getALL();
		List<JobTitle> roles = roleDAO.getALL();
		model.addAttribute("companies", companies);
		model.addAttribute("roles", roles);
		List<City> cities = cityDAO.getALL();
		model.addAttribute("cities", cities);

		return "admin/employee/employeeeditform";
	}

	// 显示候选人详细信息页面
	@RequestMapping(value = "admin/employee/detail.page", method = RequestMethod.GET)
	public String employeeDetail(HttpServletRequest request, Model model) {

		String empId = request.getParameter("empid");
		if (StringUtils.hasText(empId)) {
			Employee emp = empDAO.getById(Integer.parseInt(empId));
			model.addAttribute("employee", emp);
		} else {
			return "admin/errorpage";
		}

		List<Company> companies = companyDAO.getALL();
		List<JobTitle> roles = roleDAO.getALL();
		model.addAttribute("companies", companies);
		model.addAttribute("roles", roles);
		List<City> cities = cityDAO.getALL();
		model.addAttribute("cities", cities);

		return "admin/employee/employeedetail";
	}

	// 显示归一化公司名页面
	@AuditIt(module = "employee", action = "normaliseEmployee", description = " the employee normalise page")
	@RequestMapping(value = "admin/employee/normalise.page", method = RequestMethod.GET)
	public String normaliseCompany(HttpServletRequest request, Model model) {

		String empId = request.getParameter("empid");
		if (StringUtils.hasText(empId)) {
			Employee emp = empDAO.getById(Integer.parseInt(empId));
			model.addAttribute("employee", emp);
		} else {
			return "admin/errorpage";
		}

		List<Company> companies = companyDAO.getALL();
		List<Domain> domains = domainDAO.getAllSubDomain();
		model.addAttribute("companies", companies);
		model.addAttribute("domains", domains);

		return "admin/employee/companynormalise";
	}

	// 搜索数据
	@RequestMapping(value = "admin/employee/search.do", method = RequestMethod.POST)
	public @ResponseBody jqGridResponseObject<Employee> searchEmployee(jqGridRequestObject request, String sname,
			Integer scompanyid, String sphone) {

		jqGridResponseObject<Employee> msg = new jqGridResponseObject<Employee>();

		long page = request.getPage();
		long pagesize = request.getRows();

		long totalrows = request.getTotalrows();
		long totalpages = 0;

		// 需要分页和计算总数
		if (totalrows == 0) {
			totalrows = empDAO.getCountOfAll(sname, scompanyid, sphone);
		}
		totalpages = jqGridResponseObject.calTotalPage(totalrows, pagesize);

		// 起始位置
		long start = 0;
		start = (page - 1) * pagesize;

		// 获取数据
		List<Employee> list = empDAO.getAllWithLimit(sname, scompanyid, sphone, start, pagesize);

		// 设置返回的数据
		msg.setPage(page);
		msg.setTotal(totalpages);
		msg.setRecords(totalrows);
		msg.setRows(list);

		return msg;
	}

	// 更新候选人信息
	@AuditIt(module = "employee", action = "editEmployee", description = " the employee edit action")
	@RequestMapping(value = "admin/employee/update.do", method = RequestMethod.POST)
	public @ResponseBody ErrorMsg updateEmployee(HttpServletRequest request, Employee emp) {
		ErrorMsg msg = new ErrorMsg();

		if (emp == null) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定候选人信息");
			return msg;
		}
		if (emp.getEmpid() < 0) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定候选人信息");
			return msg;
		}

		Employee employee = empDAO.getById(emp.getEmpid());
		if (employee == null) {
			msg.setErrorcode("500101");
			msg.setMsg("没有该候选人");
			return msg;
		}

		int companyid = employee.getCompanyId();
		// if(companyid != emp.getCompanyId()) {
		Company cp = companyDAO.getById(companyid);
		employee.setCompanyName(cp.getName());
		employee.setDomainId(cp.getDomain());

		// employee.setDomainName();
		// }
		// 更新数据
		employee.setName(emp.getName());
		employee.setAge(emp.getAge());
		employee.setPhone(emp.getPhone());
		employee.setWorkage(emp.getWorkage());
		employee.setInservice(emp.getInservice());
		employee.setRoleId(emp.getRoleId());
		employee.setCityId(emp.getCityId());
		employee.setCompanyId(emp.getCompanyId());
		// employee.setDomainId(emp.getDomainId());
		employee.setBestdomain(emp.getBestdomain());
		employee.setExpectCompany1(emp.getExpectCompany1());
		employee.setExpectCompany2(emp.getExpectCompany2());
		employee.setExpectCompany3(emp.getExpectCompany3());
		employee.setExpectJob(emp.getExpectJob());
		employee.setIntentTime(emp.getIntentTime());

		int result = 0;
		result = personDAO.update(employee);
		if (result == -1) {
			msg.setErrorcode("50001");
			msg.setMsg("更新数据出错");
			return msg;
		}
		result = empDAO.update(employee);
		if (result == -1) {
			msg.setErrorcode("50001");
			msg.setMsg("更新数据出错");
			return msg;
		}

		msg.setErrorcode("0");
		msg.setMsg("更新数据成功");
		msg.setData(emp);
		return msg;
	}

	// 保存第二页提交的信息
	@OAuthRequired
	@RequestMapping(value = "admin/employee/create.do", method = RequestMethod.POST)
	public @ResponseBody Map<String, Object> createEmployee(HttpServletRequest request, ModelMap model, Employee emp) {

		Map<String, Object> returnMap = new HashMap<String, Object>();

		logger.debug("created employee is " + emp);

		int comid = emp.getCompanyId();
		Company company = companyDAO.getById(comid);
		String companyname = company.getName();

		// 如果该公司不存在数据库里，那么companyid为0，表明该公司需要归一化
		// Company company = companyDAO.getByName(companyname);
		// if (company == null) {
		// emp.setCompanyId(0);//
		// } else {
		// emp.setCompanyId(company.getId());
		// }
		// emp.setCompanyName(companyname);// duoyu

		// emp.setRoleId(emp.getRoleId());

		JobTitle jd = this.roleDAO.getById(emp.getRoleId());

		if (jd != null) {
			logger.debug("add job info job name is " + jd.getName());
			emp.setRoleName(jd.getName());
			emp.setRoleName(jd.getName());
		}
		emp.setCompanyName(companyname);
		// bestDomain:管理区域

		City city = cityDAO.getById(emp.getCityId());
		if (city != null) {
			emp.setCityName(city.getName());
		}
		Domain dn = domainDAO.getById(emp.getDomainId());
		if (dn != null) {

			emp.setDomainName(dn.getName());
		}

    emp.setPlatformId(1);

    int id = personDAO.save(emp);
    emp.setPersonId(id);
    int result = empDAO.save(emp);
    logger.debug("create employee : " + result);
    returnMap.put("errorcode", 0);
    returnMap.put("msg", "成功创建数据");
    return returnMap;
  }

  // 删除候选人
  @ResponseBody
  @AuditIt(module = "employee", action = "deleteEmployee", description = " the employee delete action")
  @RequestMapping(value = "admin/employee/delete.do", method = RequestMethod.GET)
  public ErrorMsg deleteEmployee(HttpServletRequest request, Integer empid) {

    ErrorMsg msg = new ErrorMsg();

    if (empid == null) {
      logger.debug("empid is null");
      msg.setErrorcode("-1");
      msg.setMsg("必须指定要删除数据");
      return msg;
    }

    int result = empDAO.delete(String.valueOf(empid));
    if (result == 1) {
      msg.setErrorcode("0");
      msg.setMsg("删除成功");
      return msg;
    }

    msg.setErrorcode("50001");
    msg.setMsg("删除失败");
    return msg;
  }

	// 归一化公司
	@ResponseBody
	@AuditIt(module = "employee", action = "normaliseEmployee", description = " the employee delete action")
	@RequestMapping(value = "admin/employee/normalise.do", method = RequestMethod.POST)
	public ErrorMsg normaliseCompany(HttpServletRequest request, Company company) {

		ErrorMsg msg = new ErrorMsg();

		Employee emp = null;

		String empId = request.getParameter("empid");
		if (StringUtils.hasText(empId)) {
			emp = empDAO.getById(Integer.parseInt(empId));
		} else {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定候选人信息");
			return msg;
		}

		if (emp == null) {
			msg.setErrorcode("500101");
			msg.setMsg("候选人不存在");
			return msg;
		}

		String op = request.getParameter("op");
		if (!StringUtils.hasText(op)) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定操作");
			return msg;
		}

		if (!(op.compareToIgnoreCase("create") == 0 || op.compareToIgnoreCase("subsitute") == 0)) {
			msg.setErrorcode("500101");
			msg.setMsg("指定操作不对");
			return msg;
		}

		if (company == null) {
			msg.setErrorcode("500101");
			msg.setMsg("提交的数据不对");
			return msg;
		}

		if (!StringUtils.hasText(company.getName())) {
			msg.setErrorcode("500101");
			msg.setMsg("必须指定公司名");
			return msg;
		}

		Company cp = companyDAO.getByName(company.getName());
		if (op.compareToIgnoreCase("subsitute") == 0) {
			if (cp == null) {
				msg.setErrorcode("500101");
				msg.setMsg("你选择的公司名并非标准化公司名，请重新尝试");
				return msg;
			}
			// 如果已经是标准化公司名，那么进行替换
			emp.setCompanyId(cp.getId());
			emp.setCompanyName(cp.getName());

			int ret = personDAO.update(emp);
			if (ret != -1) {
				msg.setErrorcode("0");
				msg.setMsg("归一化成功");
				return msg;
			}
		}

		if (op.compareToIgnoreCase("create") == 0) {
			if (cp != null) {
				msg.setErrorcode("500101");
				msg.setMsg("该公司名已经存在，请重新尝试");
				return msg;
			}

			company.setApproved(1);

			int companyid = companyDAO.save(company);
			if (companyid <= 0) {
				msg.setErrorcode("500101");
				msg.setMsg("创建公司数据失败，请重新尝试");
				return msg;
			}
			emp.setCompanyId(companyid);
			emp.setCompanyName(company.getName());

			int ret = personDAO.update(emp);
			if (ret != -1) {
				msg.setErrorcode("0");
				msg.setMsg("归一化成功");
				return msg;
			}
		}

		msg.setErrorcode("500101");
		msg.setMsg("归一化出错，请重新尝试");
		return msg;
	}

	/*
	 * @RequestMapping(value = "admin/employee/getAllEmployee.do", method =
	 * RequestMethod.POST)
	 * 
	 * @ResponseBody public JqGridPage getAllEmployees(JqGridPage page, String
	 * name, String phone) {
	 * 
	 * List<Employee> employees = empDAO.searchEmployees(name, phone);
	 * Page<Employee> emps = new PageImpl<Employee>(employees,
	 * page.toPageable(), employees.size()); page = JqGridPage.valueOf(emps);
	 * return page; }
	 * 
	 * @RequestMapping(value = "admin/employee/toView.page", method =
	 * RequestMethod.GET) public String toView(HttpServletRequest request, int
	 * id, Model model) { Employee emp = empDAO.getById(id);
	 * 
	 * model.addAttribute("employee", emp);
	 * 
	 * return "admin/employee/detail"; }
	 * 
	 * @ResponseBody
	 * 
	 * @RequestMapping(value = "admin/employee/create.do", method =
	 * RequestMethod.POST) public ErrorMsg createEmployee(Employee emp) {
	 * ErrorMsg msg = new ErrorMsg();
	 * 
	 * emp.setActive(1); Date date = new Date();
	 * emp.setCreateDate(date.getTime());
	 * 
	 * int result = empDAO.save(emp); if (result == -1) {
	 * msg.setErrorcode("50001"); msg.setMsg("can not save the employee" +
	 * emp.getName()); return msg; } msg.setErrorcode("0");
	 * msg.setMsg("success"); msg.setData(emp); return msg; }
	 * 
	 * @RequestMapping(value = "admin/employee/activate.do", method =
	 * RequestMethod.POST) public String activateEmployee(Employee emp, Model
	 * model) { emp.setActive(1); int result = empDAO.update(emp); return
	 * "admin/employee/list"; }
	 * 
	 * @RequestMapping(value = "admin/employee/inactivate.do", method =
	 * RequestMethod.POST) public String inactivateEmployee(Employee emp, int
	 * employeeId, Model model) { emp.setActive(0); int result =
	 * empDAO.update(emp); return "admin/employee/list"; }
	 */
}
